<template>
  <div class="add-container">
    <div class="add-top">
      <el-page-header @back="goBack" :content="gobacktitle"></el-page-header>
    </div>
    <div class="add-main">
      <div class="add-main-top">
        <div class="add-main-tital">
          <p>调拨单</p>
        </div>
        <div>
          <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-position="left" label-width="0.8rem"
            class="demo-ruleForm">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="调拨单号" prop="pingzhengh">
                  <el-input v-model="ruleForm.pingzhengh" disabled></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="物资区分" prop="wuziqf">
                  <el-select v-model="ruleForm.wuziqfid" @change="dataUpdate" placeholder="请选择">
                    <el-option v-for="(item, index) in wzqflist" :key="index" :label="item.mingcheng"
                      :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="物资分类" prop="wuzizy">
                  <el-select v-model="ruleForm.wuzizyid" @change="dataUpdate" placeholder="请选择">
                    <el-option v-for="(item, index) in wzzylist" :key="index" :label="item.zhuanyemc"
                      :value="item.zhuanyeid"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="主管单位" prop="zhuguandwid">
                  <el-select v-model="ruleForm.zhuguandwid" @change="dataUpdate" placeholder="请选择">
                    <el-option v-for="(item, index) in zgdwlist" :key="index" :label="item.danweimc"
                      :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="发货单位">
                  <el-select v-model="ruleForm.fahuodw" filterable placeholder="请选择">
                    <el-option v-for="(item, index) in sfdwlist" :key="index" :label="item.fawudw"
                      :value="item.fawudw"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="接收单位">
                  <el-select v-model="ruleForm.jieshoudw" filterable placeholder="请选择">
                    <el-option v-for="(item, index) in sfdwlist" :key="index" :label="item.fawudw"
                      :value="item.fawudw"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="6">
                <el-form-item label="保障时效">
                  <el-date-picker v-model="ruleForm.baozhangsx" type="date" placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>
              </el-col> -->
              <el-col :span="6">
                <el-form-item label="调拨依据">
                  <el-input v-model="ruleForm.diaoboyj"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="经办人">
                  <el-input v-model="ruleForm.jingbanr"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="18">
                <el-form-item label="备注">
                  <el-input type="textarea" rows="1" v-model="ruleForm.beizhu"></el-input>
                </el-form-item>
              </el-col>


            </el-row>
          </el-form>
        </div>
      </div>
      <div class="add-main-list">
        <div class="list-button-group">
          <div class="button-item">
            <el-button type="primary" icon="el-icon-plus" @click="DialogOpenWuzi()">
              新增
            </el-button>
          </div>
          <div class="button-item">
            <el-button type="danger" icon="el-icon-delete" @click="delwzDetail">
              删除
            </el-button>
          </div>
          <!-- <div class="button-item">
            <el-button type="primary" icon="el-icon-s-check" @click="importShow = true">
              导入调拨单明细
            </el-button>
          </div>
          <div class="button-item">
            <el-button type="primary" icon="el-icon-s-check">
              下载模板
            </el-button>
          </div> -->
        </div>
        <div class="table-list" id="table-list">
          <ux-grid border show-overflow ref="plxTable" keep-source :height="tabheight" :highlightCurrentRow="false"
            widthResize :rules="ruleslist" @selection-change="selectChange"
            :edit-config="{ trigger: 'click', mode: 'row' }">
            <ux-table-column type="checkbox" width="50" />
            <ux-table-column type="index" title="序号" width="50"></ux-table-column>
            <!-- <ux-table-column field="wuzibm" title="物资代码"></ux-table-column> -->
            <ux-table-column field="wuzimc" title="物资名称"></ux-table-column>
            <ux-table-column field="guigexh" title="规格型号"></ux-table-column>
            <ux-table-column field="kucunsl" title="库存数量"></ux-table-column>
            <ux-table-column field="wuzisl" title="物资数量" :edit-render="{ autofocus: '.el-input__inner' }">
              <template v-slot:edit="scope">
                <el-input v-model.trim="scope.row.wuzisl" type="number" :min="0" placeholder="请输入数量"
                  @keyup.native="scope.row.wuzisl = oninput(scope.row.wuzisl)" />
              </template>
            </ux-table-column>
            <ux-table-column show-overflow-tooltip field="cankaojg" title="单价(元)"></ux-table-column>
            <ux-table-column field="picih" title="批次号"></ux-table-column>
            <ux-table-column show-overflow-tooltip field="shengchancj" title="生产厂家"></ux-table-column>
            <ux-table-column show-overflow-tooltip field="shengchanrq" title="生产日期"> </ux-table-column>
            <!-- <ux-table-column field="kcsl" title="实际出库数量" :edit-render="{ autofocus: '.el-input__inner' }">
              <template v-slot:edit="scope">
                <el-input v-model.trim="scope.row.kcsl" type="number" :min="1" placeholder="请输入库存数量"
                  @keyup.native="scope.row.sl = oninput(scope.row.sl)" />
              </template>
            </ux-table-column> -->
          </ux-grid>
          <div class="submit-button">
            <el-button type="primary" icon="el-icon-circle-check" @click="submitForm('ruleForm')">
              确认
            </el-button>
            <el-button type="info" icon="el-icon-delete" @click="goBack">取消</el-button>
          </div>
        </div>
      </div>
    </div>
    <!--添加 物资 -->
    <page-1-add-wuzi ref="wuzi-dialog" @fetch-data="fetchData" :formData="ruleForm"></page-1-add-wuzi>
    <!-- 导入文件start -->
    <el-dialog :close-on-click-modal="false" :visible.sync="importShow" destroy-on-close title="导入文件" class="m-dialog"
      :append-to-body="true">
      <upload-wz api-url="/chukudbd/importChukudbd" @success="uploadSuccess" />
    </el-dialog>
  </div>
</template>
<script>
import { SaveChukudbd, GetChukudbdPageByid, QueryChukudbdPage } from '@/api/exwarehouse'
import { queryFWList } from '@/api/fawudw'
import UploadWz from './uploadWz.vue'
import page1AddWuzi from './page1AddWuzi.vue'
export default {
  name: 'Page1Add',
  components: { UploadWz, page1AddWuzi },
  props: {
    gobacktitle: {
      type: String,
      default: '新增',
      required: true,
    },
    datarow: {
      type: Object,
      default: function () {
        return {}
      },
    },
  },
  data() {
    const CknumRules = ({ cellValue, rule, row }) => {
      if (!cellValue) {
        return new Error('出库数量必填')
      } else if (cellValue > row.kucunsl) {
        return new Error(`出库数量不得大于计划出库数量`)
      }
    }
    return {
      show: true,
      ruleForm: {},
      wzqflist: [],
      wzzylist: [],
      zgdwlist: [],
      rules: {
        pingzhengh: [{ required: true, message: '请输入入库单号', trigger: 'blur' }],
      },
      ruleslist: {
        wzmc: [{ required: true, message: '请输入物资名称', trigger: 'blur' }],
        wuzisl: [{ required: true, validator: CknumRules, trigger: 'blur' }],
        danj: [{ required: true, message: '请输入单价', trigger: 'blur' }],
      },
      tabheight: 500,
      importShow: false,
      insertData: [],
      sfdwlist: []
    }
  },
  async created() {
    let list = await QueryChukudbdPage({ 'startTime': this.$util.changeBZTime() })
    this.ruleForm.pingzhengh = this.$util.addPreZero(list.data.total, 'CK')
    this.wzqflist = await this.$util.getWzqflist()
    this.zgdwlist = await this.$util.getZgdw()
    this.wzzylist = await this.$util.getWzzy()
    let { data } = await queryFWList({})
    this.sfdwlist = data
    if (this.gobacktitle == '新增') {
      this.ruleForm.wuziqfid = this.wzqflist[1].id
      this.ruleForm.zhuguandwid = this.zgdwlist[0].id
      this.ruleForm.wuzizyid = this.wzzylist[0].zhuanyeid
    }

  },
  async mounted() {
    if (this.gobacktitle == '编辑') {
      let { data } = await GetChukudbdPageByid({ id: this.datarow.id })
      this.ruleForm = data
    }
    let height = document.getElementById("table-list").offsetHeight
    this.tabheight = height - 140
    this.$nextTick(() => {
      this.$refs.plxTable.reloadData(this.ruleForm.chukudbdmxList)
    })
  },
  methods: {
    dataUpdate() {
      this.$forceUpdate()
    },
    goBack() {
      this.$parent.addshow = false
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ruleForm.cangkuid = this.$store.getters['user/cangkuid']
          this.ruleForm.chukudbdmxList = this.$refs.plxTable.getTableData().fullData
          const mxLen = this.$refs.plxTable.getTableData().fullData

          if (mxLen.length == 0) {
            this.$message({
              message: '请添加明细',
              type: 'warning',
            });
            return;
          }
          this.$refs.plxTable.validate(true).then(async (data) => {
            if (data) {
              // 有错误
            }
            else {
              const msg = await SaveChukudbd(this.ruleForm)
              this.$message({
                message: msg.msg,
                type: 'success',
              });
              // if (this.gobacktitle == '添加') {
              //   this.resetForm();//重置表单
              // }
              this.goBack()
              this.$parent.resetlist()
            }
          })
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    DialogOpenWuzi(row) {
      this.$refs['wuzi-dialog'].listQuery.wuzizy = this.ruleForm.wuzizyid
      this.$refs['wuzi-dialog'].listQuery.wuziqfid = this.ruleForm.wuziqfid
      this.$refs['wuzi-dialog'].showEdit(row)
      this.$refs['wuzi-dialog'].getData()
    },
    selectChange(e) { },
    // 添加插入行
    async insertEvent(row) {
      let record = this.insertData
      // 加入行, 表示加入行的row对象，row为空则插入第一行，为-1插入最后一行
      let { row: newRow } = await this.$refs.plxTable.insertRow(record)
      // 激活单元格编辑
      await this.$refs.plxTable.setActiveRow(newRow)
    },
    delwzDetail() {
      this.$refs.plxTable.remove(this.$refs.plxTable.getCheckboxRecords())
    },
    uploadSuccess(res) {
      this.ruleForm.chukudbdmxList = res.chukudbdmxDto
      this.importShow = false
      this.$nextTick(() => {
        this.$refs.plxTable.reloadData(this.ruleForm.chukudbdmxList)
      })
    },
    oninput(num) {
      return num.replace(/\D/g, '')
    },
    fetchData(data) {
      this.insertData = []
      data.forEach(item => {
        this.insertData.push({
          wuzibm: item.wuzibm,
          wuzimc: item.wuzimc,
          wuziid: item.wuziid,
          guigexh: item.guigexh,
          kucunsl: item.shuliang,
          cankaojg: item.danjia,
          picih: item.picih,
          shengchancj: item.shengchancj,
          shengchanrq: item.shengchanrq,
          kufangid: item.kufangid
        })
      });
      this.insertEvent();
    }
  },
}
</script>
<style lang="scss" scoped>
.add-container {
  position: fixed;
  left: 0;
  top: .75rem;
  width: 100%;
  height: 100%;
  z-index: 1000;
  background-color: #f6f8f9;
  padding: 0 .2rem 1rem .2rem;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .add-top {
    padding: .10rem 0;

    ::v-deep .el-page-header__title {
      font-size: .16rem !important;
    }
  }

  .add-main {
    flex: 1;
    font-weight: bold;
    display: flex;
    flex-direction: column;
    overflow: auto;

    .add-main-top {
      padding: .2rem;
      background: #fff;
      border-radius: .05rem;

      .add-main-tital {
        font-size: .18rem;
        border-left: .10rem solid rgb(121, 189, 255);
        padding-left: .10rem;

        p {
          margin: 0;
        }
      }

      .search-gropu-item {
        margin-top: .20rem;
        width: 90%;
        display: flex;
        // label {
        //   white-space: nowrap;
        //   line-height: 32px;
        //   margin-right: 10px;
        // }
      }

      .el-select {
        width: 100%;
      }
    }

    .add-main-list {
      flex: 1;
      margin-top: 20px;
      background: #fff;
      padding: 20px;
      box-sizing: border-box;

      .list-button-group {
        display: flex;
        flex-direction: row;
        padding-bottom: 20px;

        .button-item {
          padding: 0px 10px;
        }

        .button-item:first-child,
        &:last-child {
          padding: 0px 10px 0 0;
        }
      }
    }

    .el-button {
      font-size: .14rem !important;
    }

    ::v-deep {
      .elx-table--header-wrapper {
        background-color: rgb(233, 243, 255);
      }

      .elx-table {
        font-size: 0.14rem !important;
      }

      .elx-body--column {
        height: .48rem !important;
        line-height: .24rem;
      }

      .elx-header--column {
        background-image: none !important;
        height: .48rem !important;
      }

      .el-date-editor.el-input,
      .el-date-editor.el-input--inner {
        width: 100% !important;
      }

      .el-form-item--small.el-form-item {
        margin-bottom: 0px;
        margin-top: 18px;
      }
    }

    .submit-button {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
}
</style>